import { PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Button, Divider, message, Input, Modal, Tag } from 'antd';
import React, { useState, useRef } from 'react';
import debounce  from 'lodash.debounce';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import AddRoleForm from './components/AddRoleForm';
import RoleModel from './components/RoleModel';
import { RoleListParams, RoleListItem } from './data.d';
import { roleList, addRole, updateRole ,roleDel} from './service';

const { Search } = Input;

const RoleList: React.FC<{}> = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [deleteModalVisible, handleDeleteModalVisible] = useState<boolean>(false);
  const [roleModalVisible, handleRoleModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState<RoleListItem>({});
  const actionRef = useRef<ActionType>();

  //添加角色
  const addRoleComment = (role: RoleListItem) => {
    new Promise((resolve, reject) => {
      addRole(role)
        .then((res) => {
          if(res){
            if (res.code === 200) {
              const hide = message.success('添加成功');
              handleModalVisible(false);
              if (actionRef.current) {
                hide();
                actionRef.current.reload();
              }
              resolve(true);
            }else{
              message.error('添加失败，'+res.message);
              resolve(false);
            }
          }else {
            message.error('添加失败');
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('添加失败');
          reject(error);
        });
    });
  };

  //编辑角色
  const updateRoleComment = (role: RoleListItem) => {
    new Promise((resolve, reject) => {
      updateRole(role)
        .then((res) => {
          if(res){
            if (res.code === 200) {
              const hide = message.success('保存成功');
              handleModalVisible(false);
              if (actionRef.current) {
                hide();
                actionRef.current.reload();
              }
              resolve(true);
            }else {
              message.error('保存失败，'+res.message);
              resolve(false);
            }
          } else {
            message.error('保存失败');
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('保存失败');
          reject(error);
        });
    });
  };

  //【新建/编辑】对话框，确定按钮点击
  const handleUpdate = async (values: RoleListItem) => {
    if (values != null && values != undefined) {
      if (values.id != undefined) {
        //编辑角色
        updateRoleComment(values);
      } else {
        //添加角色
        addRoleComment(values);
      }
    }
  };

   //删除角色
   const delConfirm = (id: number) => {
    Modal.confirm({
      visible: deleteModalVisible,
      title: '确定删除',
      icon: <QuestionCircleOutlined />,
      content: '此角色将永久删除',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        return new Promise((resolve, reject) => {
          roleDel(id)
            .then((res) => {
              if (res.code === 200) {
                message.success('删除成功');
                handleDeleteModalVisible(false);
                actionRef.current?.reload?.();
                resolve(true);
              } else if(res.code === 4501){
                message.error('删除失败，正在使用');
                resolve(false);
              }else{
                message.error('删除失败，'+res.message);
                resolve(false);
              }
            })
            .catch((error) => {
              message.error('删除失败');
              reject(error);
            });
        });
      },
    });
  };

  const columns: ProColumns<RoleListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '角色名',
      dataIndex: 'name',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Search
              placeholder="请输入角色名称"
              onSearch={debounce(value=>{form.submit()}, 500)}
              onChange={debounce(value=>{form.submit()}, 500)}
              style={{ width: 200 }}
            />
          );
        }
        return defaultRender(_);
      },
      valueType: 'text',
    },
    {
      title: '所属机构',
      dataIndex: 'orgName',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '角色描述',
      dataIndex: 'remark',
      valueType: 'text',
      hideInSearch: true,
      ellipsis:true,
      width:250,
    },
    {
      title: '更新时间',
      dataIndex: 'datetime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '角色类型',
      dataIndex: 'scope',
      valueType: 'text',
      hideInSearch: true,
      render: (scope,record) => (
        scope=="SYSTEM"?<Tag color="#f50">SYSTEM</Tag>: 
          record.id == JSON.parse(localStorage.getItem("user")).roleId?<Tag color="#108ee9">CURRENT</Tag>:""
      )
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleRoleModalVisible(true);
              setFormValues(record);
            }}
          >
            查看权限
          </a>
          <Divider type="vertical" />
          <a
            disabled={
              (record.scope == "SYSTEM" && 
                JSON.parse(localStorage.getItem("user"))?.orgId != 10000)?true:false //条件：1.当前登录非root用户，系统角色不能删除。
            }
            onClick={() => {
              handleModalVisible(true);
              setFormValues(record);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a 
            
            disabled={
              ((record.scope == "SYSTEM" && 
                JSON.parse(localStorage.getItem("user"))?.orgId != 10000)||
                (record.id == JSON.parse(localStorage.getItem("user")).roleId))?true:false //条件：1.当前登录非root用户，系统角色不能删除。2.不能删除当前用户所属角色
            }
            onClick={() => {
              delConfirm(record.id);
            }}
          >删除</a>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<RoleListParams>
        options={false}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        pagination={{ showQuickJumper: true,defaultPageSize: 10 }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => {handleModalVisible(true);setFormValues({})}}>
            <PlusOutlined /> 新建角色
          </Button>,
        ]}
        request={(params, sorter, filter) => roleList({ ...params, sorter, filter })}
        columns={columns}
      />
      <AddRoleForm
        onSubmit={handleUpdate}
        onCancel={() => handleModalVisible(false)} 
        modalVisible={createModalVisible}
        values={formValues}
      >
        <ProTable<RoleListItem, RoleListItem>
        />
      </AddRoleForm>

      <RoleModel
        onCancel={() => handleRoleModalVisible(false)} 
        modalVisible={roleModalVisible}
        values={formValues}
      >
        <ProTable<RoleListItem, RoleListItem>
        />
      </RoleModel>

    </PageContainer>
  );
};

export default RoleList;
